package com.tsyz.shared.util;

import java.util.List;
import java.util.concurrent.ExecutorService;

/**
 * CompletableFuture演示类
 * 展示如何在企业级应用中使用CompletableFuture和自定义线程池
 */
public class CompletableFutureDemo {
    
    public static void main(String[] args) {
        // 创建线程池配置
        AsyncThreadPoolConfig.ThreadPoolProperties properties = 
                new AsyncThreadPoolConfig.ThreadPoolProperties();
        
        // 可以根据需要调整配置
        properties.setCorePoolSize(3);
        properties.setMaximumPoolSize(8);
        properties.setQueueCapacity(50);
        properties.setThreadNamePrefix("tsyz-async-");
        
        // 创建线程池
        ExecutorService threadPool = AsyncThreadPoolConfig.createThreadPool(properties);
        
        // 创建练习实例
        CompletableFuturePractice practice = new CompletableFuturePractice(threadPool);
        
        try {
            // 运行各种示例
            runBasicExample(practice) ;//- 运行基础异步任务示例
            runParallelExample(practice) ;//- 运行多任务并行处理示例
            runChainedExample(practice) ;//- 运行任务链式调用示例
            runExceptionExample(practice) ;//- 运行异常处理示例
            runCombinedExample(practice) ;//- 运行组合任务示例
        } finally {
            // 关闭线程池
            threadPool.shutdown();
        }
    }
    
    /**
     * 运行基础示例
     */
    private static void runBasicExample(CompletableFuturePractice practice) {
        System.out.println("=== 基础异步任务示例 ===");
        String result = practice.basicAsyncExample().join();
        System.out.println("结果: " + result);
        System.out.println();
    }
    
    /**
     * 运行并行任务示例
     */
    private static void runParallelExample(CompletableFuturePractice practice) {
        System.out.println("=== 多任务并行处理示例 ===");
        List<String> results = practice.parallelTasksExample(5).join();
        System.out.println("并行任务结果: " + results);
        System.out.println();
    }
    
    /**
     * 运行链式任务示例
     */
    private static void runChainedExample(CompletableFuturePractice practice) {
        System.out.println("=== 任务链式调用示例 ===");
        String result = practice.chainedTasksExample("hello").join();
        System.out.println("链式调用结果: " + result);
        System.out.println();
    }
    
    /**
     * 运行异常处理示例
     */
    private static void runExceptionExample(CompletableFuturePractice practice) {
        System.out.println("=== 异常处理示例 ===");
        String result1 = practice.exceptionHandlingExample(false).join();
        System.out.println("正常情况结果: " + result1);
        
        String result2 = practice.exceptionHandlingExample(true).join();
        System.out.println("异常情况结果: " + result2);
        System.out.println();
    }
    
    /**
     * 运行组合任务示例
     */
    private static void runCombinedExample(CompletableFuturePractice practice) {
        System.out.println("=== 组合任务示例 ===");
        String result = practice.combinedTasksExample().join();
        System.out.println("组合任务结果: " + result);
        System.out.println();
    }
}
